import React, { useMemo, useState } from 'react';
import { Button, Popconfirm, Table, Form, Input } from 'antd';
import { PageType } from '../constant';
import Styles from './index.less';

interface ChannelCodeType {
  pageType: string;
  channelCodeList: any[];
  setChannelCodeList: (arr: any[]) => void;
  detailRecord: Record<string, string>;
}

// eslint-disable-next-line react/function-component-definition
const EditableCell: React.FC<any> = ({
  editing,
  dataIndex,
  title,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = <Input placeholder="请输入" />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item name={dataIndex} style={{ margin: 0 }}>
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

export function ChannelCode({
  pageType,
  channelCodeList,
  setChannelCodeList,
  detailRecord,
}: ChannelCodeType) {
  const [editingKey, setEditingKey] = useState('');
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({ current: 1, size: 10 });

  const onDelete = (id: string) => {
    const index = channelCodeList.findIndex((item) => id === item.key);
    channelCodeList.splice(index, 1);
    setChannelCodeList([...channelCodeList]);
  };

  const add = () => {
    form.resetFields();
    const obj = { key: '' };
    obj.key = (Math.floor(Math.random() * (100000000 - 1)) + 1).toString();
    setChannelCodeList([obj, ...channelCodeList]);
    setEditingKey(obj.key);
  };

  const edit = (record: Record<string, string>) => {
    form.setFieldsValue({
      a: record.a,
      b: record.b,
      c: record.c,
    });
    setEditingKey(record.key);
  };

  const onSave = async () => {
    const data = await form.validateFields();

    const index = channelCodeList.findIndex((item) => item.key === editingKey);
    // eslint-disable-next-line no-param-reassign
    channelCodeList[index] = { ...data, key: editingKey };
    setChannelCodeList([...channelCodeList]);
    setEditingKey('');
  };

  const Colnums: any[] = useMemo(() => {
    const arr: any[] = [
      {
        title: '渠道码',
        dataIndex: 'a',
        align: 'center',
        width: 100,
        editable: true,
      },
      {
        title: '销售',
        dataIndex: 'b',
        align: 'center',
        width: 100,
        editable: true,
      },
      {
        title: '联系电话',
        dataIndex: 'c',
        align: 'center',
        width: 200,
        editable: true,
      },
    ];
    if (pageType !== PageType.Detail) {
      arr.push({
        title: '操作',
        dataIndex: '',
        align: 'center',
        width: 100,
        fixed: 'right',
        render: (key: string, record: Record<string, string>) => (
          <div className={Styles.operationBtn}>
            {editingKey === record.key ? (
              <>
                <span onClick={onSave} aria-hidden>
                  保存
                </span>
                <span onClick={() => setEditingKey('')} aria-hidden>
                  取消
                </span>
              </>
            ) : (
              <>
                <span onClick={() => edit(record)} aria-hidden="true">
                  编辑
                </span>
                <Popconfirm
                  placement="topLeft"
                  title="你确定要删除这条数据吗？"
                  onConfirm={() => onDelete(record.key)}
                  okText="确定"
                  cancelText="取消"
                >
                  <span>删除</span>
                </Popconfirm>
              </>
            )}
          </div>
        ),
      });
    }
    return arr;
  }, [pageType, editingKey]);

  const mergedColumns = Colnums.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: any) => ({
        record,
        dataIndex: col.dataIndex,
        title: col.title,
        // eslint-disable-next-line no-shadow
        editing: record.key === editingKey,
      }),
    };
  });

  return (
    <div className={Styles.accordingToRecords}>
      <div className={Styles.titleBox}>渠道码</div>
      <div className={Styles.content}>
        {pageType !== PageType.Detail && (
          <div className={Styles.btnList}>
            <Button type="primary" size="small" onClick={add}>
              新增
            </Button>
          </div>
        )}
        <Form form={form} component={false}>
          <Table
            components={{
              body: {
                cell: EditableCell,
              },
            }}
            bordered
            rowClassName="editable-row"
            columns={mergedColumns}
            dataSource={channelCodeList}
            pagination={{
              onChange: () => {
                setEditingKey('');
              },
            }}
          />
        </Form>
      </div>
    </div>
  );
}
